/*
 * @Description: 单位导航包裹组件
 * @Author: Rfan
 * @Date: 2022-02-10 13:40:29
 * @LastEditTime: 2023-02-27 09:27:35
 */

import { Key, useEffect, useState } from 'react';
import { Tree } from 'antd';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { fetchDepartmentListByUnitId } from '@/api/department';
import { useOrgAndUserContext } from '../contexts/OrgAndUserContext';
import { selectItemByKey } from '@/utils/list';
import { appState } from '@/store/mobx';
import styles from '../styles/departmentSidebar.module.scss';

const cx = classNames.bind(styles);

/**
 * @description: 部门导航组件
 * @return {*}
 */
const DepartmentSidebar = (): any => {
  const { departmentTree, setDepartmentList, setSelectDepartment, clearUserList } =
    useOrgAndUserContext();
  // 选中的节点key，TODO：有子节点是需要测试
  const [selectKey, setSelectKey] = useState([]);

  // 加载时获取单位列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    const { unitId } = appState;

    if (unitId) {
      // 切换单位时清空选中部门与用户列表
      setSelectDepartment({});
      clearUserList();
      fetchDepartmentListByUnitId(unitId).then((res) => {
        const _departmentList = res.data;
        setDepartmentList(_departmentList);
        _departmentList.length > 0 && setSelectKey([_departmentList[0].id]);
        _departmentList.length > 0 &&
          setSelectDepartment(selectItemByKey(_departmentList[0].id, _departmentList));
      });
    }
  }, [appState.unitId]);

  /**
   * @description:Tree组件设置为受控组件，选中节点时设置选中的key并将选中的内容返回出去
   * @param {React.Key[]} selectedKeys
   * @param {any} info
   */
  const onSelect = (selectedKeys: Key[], info: any) => {
    console.log('selected', selectedKeys, info);
    if (selectedKeys.length > 0) {
      setSelectKey(selectedKeys);
      setSelectDepartment(info.node);
    }
  };

  return (
    <div className={cx('container')}>
      <h6 className={cx('department-header')}>部门列表</h6>
      <div className="department-navs">
        <Tree
          onSelect={onSelect}
          treeData={departmentTree}
          fieldNames={{
            title: 'deptName',
            key: 'id'
          }}
          selectedKeys={selectKey}
        />
      </div>
    </div>
  );
};

export default observer(DepartmentSidebar);
